package com.kyubi.tagger.taggers;

import java.util.Arrays;
import java.util.Vector;

import com.kyubi.common.config.ConfigKeys;
import com.kyubi.common.config.Configuration;
import com.kyubi.tagger.ITagger;
import com.kyubi.tagger.decorators.PorterStemmer;

import edu.stanford.nlp.parser.lexparser.LexicalizedParser;
import edu.stanford.nlp.trees.Tree;

/**
 * The class representing the decorator which is a wrapper over the
 * Stanford parser.
 * 
 * @author anand
 *
 */
public class StanfordTreeTagger implements ITagger {

	private ITagger tagger;
	private Configuration config;
	private LexicalizedParser lp;
	
	/**
	 * 
	 * @param tagger	the previous ITagger object being decorated
	 */
	public StanfordTreeTagger(ITagger tagger) {
		this.tagger = tagger;
		config = Configuration.getSingleton();
		lp = new LexicalizedParser(config.get(ConfigKeys.BASEURL) + config.get(ConfigKeys.PCFG_PATH));
	    lp.setOptionFlags(new String[]{"-maxLength", "80", "-retainTmpSubcategories"});
	}
	
	/**
	 * Instantiate the tagger as a standalone and not a decorator.
	 */
	public StanfordTreeTagger() {
		config = Configuration.getSingleton();
		lp = new LexicalizedParser(config.get(ConfigKeys.BASEURL) + config.get(ConfigKeys.PCFG_PATH));
	    lp.setOptionFlags(new String[]{"-maxLength", "80", "-retainTmpSubcategories"});
	}
	
	/**
	 * Reset the tagger being decorated.
	 * @param newTagger	the new tagger
	 */
	public void resetTagger(ITagger newTagger){
		this.tagger = newTagger;
	}
	
	/**
	 * @see com.kyubi.tagger.ITagger
	 */
	public Vector<String> getTaggedValues() {
		Vector<String> tValues = tagger.getTaggedValues();
		Vector<String> rValues = new Vector<String>();
		
		for(String value : tValues) {
		    String[] tokens = value.split("[ ]+");
		    Tree parse = (Tree) lp.apply(Arrays.asList(tokens));
		    String str = parse.toString();
		    rValues.add(str);
		}
		
		return rValues;
	}
	
	/**
	 * @see com.kyubi.tagger.ITagger
	 */
	public Vector<String> getOriginalValues() {
		Vector<String> dataVect = tagger.getOriginalValues();
		return dataVect;
	}
	
	/**
	 * Function the parse a given line into a PennTree representation.
	 * @param line	the line to be parsed
	 * @return	the PennTree format tree representation
	 */
	public String parse(String line) {
		String[] tokens = line.split("[ ]+");
	    Tree parse = (Tree) lp.apply(Arrays.asList(tokens));
	    String str = parse.toString();
	    
	    return str;
	}

	public static void main(String[] args) {
		try {
			Configuration c = Configuration.getSingleton(args[2]);
			ITagger tagr = new StanfordTreeTagger(new PorterStemmer(new XMLWrapper("/Users/anand/kyubi/resources/xml/test.xml")));
			Vector<String> r = tagr.getTaggedValues();
			for(int i=0; i<r.size(); i++) {
				System.out.println(r.get(i));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
